package com.lilicould.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可以留空
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String uri = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();

        // 白名单：允许访问的路径（无需登录）
        boolean isLoginPage = uri.equals(contextPath + "/page/login.jsp");
        boolean isLoginController = uri.equals(contextPath + "/api/login");

        // 如果是白名单中的页面，直接放行
        if (isLoginPage || isLoginController) {
            chain.doFilter(request, response);
            return;
        }

        // 检查 session 中是否存在 account 对象并且role属性不为空
        if (session == null || session.getAttribute("userNo") == null || session.getAttribute("role") == null) {
            // 用户未登录，跳转到登录页面
            httpRequest.getRequestDispatcher("/page/login.jsp").forward(httpRequest, httpResponse);
            return; // 添加return以防止继续执行
        }

        // 用户已登录，放行其他请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁方法，可以留空
    }
}